import { RenderEngine } from './renderer/RenderEngine';
import { PhysicsEngine } from './physics/PhysicsEngine';
import { Player } from './entity/Player';
import { Enemy } from './entity/Enemy';
import { Bullet } from './entity/Bullet';
import { Obstacle } from './entity/Obstacle';
import { Texture } from 'pixi.js';
import { useGameStore } from '../store/gameStore';

export class GameManager {
  private renderEngine: RenderEngine;
  private physicsEngine: PhysicsEngine;
  private player: Player | null;
  private enemies: Map<string, Enemy>;
  private bullets: Map<string, Bullet>;
  private obstacles: Map<string, Obstacle>;
  private pressedKeys: Set<string>;
  private lastBulletTime: number;
  private bulletCooldown: number;
  private gameTime: number;
  private entityIdCounter: number;

  constructor(renderEngine: RenderEngine, physicsEngine: PhysicsEngine) {
    this.renderEngine = renderEngine;
    this.physicsEngine = physicsEngine;
    this.player = null;
    this.enemies = new Map();
    this.bullets = new Map();
    this.obstacles = new Map();
    this.pressedKeys = new Set();
    this.lastBulletTime = 0;
    this.bulletCooldown = 250; // 子弹冷却时间（毫秒）
    this.gameTime = 0;
    this.entityIdCounter = 0;

    // 设置键盘事件监听
    this.setupInputListeners();
  }

  // 生成唯一实体ID
  private generateEntityId(prefix: string): string {
    return `${prefix}_${this.entityIdCounter++}`;
  }

  // 设置输入监听器
  private setupInputListeners(): void {
    // 键盘按下事件
    window.addEventListener('keydown', (event) => {
      this.pressedKeys.add(event.code);

      // 冲刺触发（空格键）
      if (event.code === 'Space' && this.player) {
        this.player.dash();
      }
    });

    // 键盘释放事件
    window.addEventListener('keyup', (event) => {
      this.pressedKeys.delete(event.code);
    });

    // 鼠标点击事件（射击）
    window.addEventListener('click', (event) => {
      this.handleShooting(event.clientX, event.clientY);
    });
  }

  // 初始化游戏
  public initGame(): void {
    // 创建玩家
    this.createPlayer(window.innerWidth / 2, window.innerHeight / 2);

    // 创建测试障碍物
    this.createObstacle(300, 300);
    this.createObstacle(500, 400);
    this.createObstacle(200, 500);

    // 创建测试敌人
    this.createEnemy(100, 100);
    this.createEnemy(700, 100);
    this.createEnemy(400, 600);

    // 启动游戏循环
    this.renderEngine.startGameLoop(this.update.bind(this));
  }

  // 创建玩家
  private createPlayer(x: number, y: number): void {
    const playerId = this.generateEntityId('player');
    
    // 创建玩家精灵
    const playerSprite = this.renderEngine.addGameObject(playerId, Texture.WHITE);
    playerSprite.width = 32;
    playerSprite.height = 32;
    playerSprite.tint = 0x00FFFF; // 青色

    // 创建玩家物理体
    const playerBody = this.physicsEngine.addBody(playerId, {
      position: { x, y },
      width: 32,
      height: 32,
      isStatic: false,
      friction: 0.1,
      restitution: 0.2,
    });

    // 创建玩家实体
    this.player = new Player({
      id: playerId,
      x,
      y,
      width: 32,
      height: 32,
      sprite: playerSprite,
      body: playerBody,
      speed: 5,
      dashSpeed: 15,
      dashDuration: 150,
      dashCooldown: 1000,
    });
  }

  // 创建敌人
  private createEnemy(x: number, y: number): void {
    const enemyId = this.generateEntityId('enemy');
    
    // 创建敌人精灵
    const enemySprite = this.renderEngine.addGameObject(enemyId, Texture.WHITE);
    enemySprite.width = 32;
    enemySprite.height = 32;
    enemySprite.tint = 0xFF0000; // 红色

    // 创建敌人物理体
    const enemyBody = this.physicsEngine.addBody(enemyId, {
      position: { x, y },
      width: 32,
      height: 32,
      isStatic: false,
      friction: 0.1,
      restitution: 0.2,
    });

    // 创建敌人实体
    const enemy = new Enemy({
      id: enemyId,
      x,
      y,
      width: 32,
      height: 32,
      sprite: enemySprite,
      body: enemyBody,
      speed: 2,
      health: 100,
      damage: 10,
      detectionRadius: 200,
      attackRadius: 50,
      attackCooldown: 1000,
    });

    // 设置目标为玩家
    if (this.player) {
      enemy.setTarget(this.player);
    }

    // 添加到敌人集合
    this.enemies.set(enemyId, enemy);
  }

  // 创建子弹
  private createBullet(x: number, y: number, directionX: number, directionY: number): void {
    const bulletId = this.generateEntityId('bullet');
    
    // 创建子弹精灵
    const bulletSprite = this.renderEngine.addGameObject(bulletId, Texture.WHITE);
    bulletSprite.width = 8;
    bulletSprite.height = 4;
    bulletSprite.tint = 0xFFFF00; // 黄色

    // 创建子弹物理体
    const bulletBody = this.physicsEngine.addBody(bulletId, {
      position: { x, y },
      width: 8,
      height: 4,
      isStatic: false,
      isSensor: true, // 子弹不会产生物理反应，只检测碰撞
    });

    // 创建子弹实体
    const bullet = new Bullet({
      id: bulletId,
      x,
      y,
      width: 8,
      height: 4,
      sprite: bulletSprite,
      body: bulletBody,
      damage: 20,
      speed: 10,
      lifeTime: 2000,
      direction: { x: directionX, y: directionY },
    });

    // 添加到子弹集合
    this.bullets.set(bulletId, bullet);
  }

  // 创建障碍物
  private createObstacle(x: number, y: number): void {
    const obstacleId = this.generateEntityId('obstacle');
    
    // 创建障碍物精灵
    const obstacleSprite = this.renderEngine.addGameObject(obstacleId, Texture.WHITE);
    obstacleSprite.width = 48;
    obstacleSprite.height = 48;
    obstacleSprite.tint = 0x8B4513; // 棕色

    // 创建障碍物物理体
    const obstacleBody = this.physicsEngine.addBody(obstacleId, {
      position: { x, y },
      width: 48,
      height: 48,
      isStatic: true,
    });

    // 创建障碍物实体
    const obstacle = new Obstacle({
      id: obstacleId,
      x,
      y,
      width: 48,
      height: 48,
      sprite: obstacleSprite,
      body: obstacleBody,
      health: 50,
      isDestructible: true,
      dropChance: 0.3,
      breakAnimationDuration: 500, // 添加破坏动画持续时间
    });

    // 添加到障碍物集合
    this.obstacles.set(obstacleId, obstacle);
  }

  // 处理射击
  private handleShooting(mouseX: number, mouseY: number): void {
    if (!this.player) return;

    const currentTime = Date.now();
    if (currentTime - this.lastBulletTime < this.bulletCooldown) {
      return; // 子弹冷却中
    }

    // 更新上次射击时间
    this.lastBulletTime = currentTime;

    // 获取玩家位置
    const playerPos = this.player.getPosition();

    // 计算射击方向
    const dirX = mouseX - playerPos.x;
    const dirY = mouseY - playerPos.y;
    const length = Math.sqrt(dirX * dirX + dirY * dirY);

    // 创建子弹
    this.createBullet(
      playerPos.x,
      playerPos.y,
      dirX / length,
      dirY / length
    );
  }

  // 检测碰撞
  private checkCollisions(): void {
    // 子弹与敌人碰撞
    for (const bullet of this.bullets.values()) {
      if (!bullet.isEntityActive()) continue;

      // 检查与敌人的碰撞
      for (const enemy of this.enemies.values()) {
        if (!enemy.isEntityActive()) continue;

        if (bullet.intersects(enemy)) {
          bullet.onCollision(enemy);
          break; // 子弹已消失，不再检查其他碰撞
        }
      }

      // 检查与障碍物的碰撞
      for (const obstacle of this.obstacles.values()) {
        if (!obstacle.isEntityActive()) continue;

        if (bullet.intersects(obstacle)) {
          bullet.onCollision(obstacle);
          obstacle.takeDamage(bullet.getDamage());
          break; // 子弹已消失，不再检查其他碰撞
        }
      }
    }

    // 玩家与敌人碰撞
    if (this.player && this.player.isEntityActive()) {
      for (const enemy of this.enemies.values()) {
        if (!enemy.isEntityActive()) continue;

        if (this.player.intersects(enemy) && !this.player.isInvulnerableState()) {
          // 玩家受到伤害
          // 这里可以调用游戏状态管理器来处理玩家受伤
          const gameStore = useGameStore.getState();
          gameStore.takeDamage(10); // 假设敌人造成10点伤害
        }
      }
    }
  }

  // 清理不活跃的实体
  private cleanupInactiveEntities(): void {
    // 清理不活跃的子弹
    for (const [id, bullet] of this.bullets.entries()) {
      if (!bullet.isEntityActive()) {
        this.renderEngine.removeGameObject(id);
        this.physicsEngine.removeBody(id);
        bullet.destroy();
        this.bullets.delete(id);
      }
    }

    // 清理不活跃的敌人
    for (const [id, enemy] of this.enemies.entries()) {
      if (!enemy.isEntityActive()) {
        this.renderEngine.removeGameObject(id);
        this.physicsEngine.removeBody(id);
        enemy.destroy();
        this.enemies.delete(id);

        // 敌人死亡时增加分数和经验
        const gameStore = useGameStore.getState();
        gameStore.updateScore(100); // 每个敌人100分
        gameStore.gainExperience(20); // 每个敌人20经验
      }
    }

    // 清理不活跃的障碍物
    for (const [id, obstacle] of this.obstacles.entries()) {
      if (!obstacle.isEntityActive()) {
        this.renderEngine.removeGameObject(id);
        this.physicsEngine.removeBody(id);
        obstacle.destroy();
        this.obstacles.delete(id);

        // 检查是否应该掉落物品
        if (obstacle.shouldDropItem()) {
          // 在这里实现物品掉落逻辑
          console.log('障碍物掉落了物品！');
        }
      }
    }
  }

  // 游戏更新循环
  private update(delta: number): void {
    // 更新游戏时间
    this.gameTime += delta;

    // 更新游戏状态存储中的时间
    const gameStore = useGameStore.getState();
    gameStore.updateGameTime(delta);

    // 处理玩家输入
    if (this.player && this.player.isEntityActive()) {
      this.player.handleMovement(this.pressedKeys);
      this.player.update(delta);

      // 更新摄像机位置，跟随玩家
      const playerPos = this.player.getPosition();
      this.renderEngine.updateCamera(playerPos.x, playerPos.y);
    }

    // 更新敌人
    for (const enemy of this.enemies.values()) {
      enemy.update(delta);
    }

    // 更新子弹
    for (const bullet of this.bullets.values()) {
      bullet.update(delta);
    }

    // 检测碰撞
    this.checkCollisions();

    // 清理不活跃的实体
    this.cleanupInactiveEntities();
  }
}